package com.cs.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.cs.entity.Course;
import com.cs.entity.Grade;
import com.cs.entity.Student;
import com.cs.entity.Teacher;
import com.cs.service.StudentServiceImpl;
import com.cs.service.TeacherServiceImpl;

@Controller
public class TeacherController {
	@Resource
	private TeacherServiceImpl tImpl;
	@Resource
	private StudentServiceImpl sImpl;
	
	//教师登录
	@RequestMapping("tealogin")
	public Object teacherLogin(HttpServletRequest request,HttpServletResponse response) throws IOException{
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		PrintWriter out = response.getWriter();
		Teacher teacher = this.tImpl.teacherLogin(username, password);
		if (teacher!=null) {
			request.getSession().setAttribute("teacher", teacher);
			out.print("<script language='javascript'>alert('登录成功');window.location.href='teaindex.jsp'</script>");
		}
		out.print("<script language='javascript'>alert('用户名或密码错误');window.location.href='login.jsp'</script>");
		return out;
	}
	//退出登录
	@RequestMapping("logout")
	public String logout(HttpServletRequest request){
		request.getSession().invalidate();;
		return "/login.jsp";
	}
	//查询个人信息（根据id）
	@RequestMapping("findteacher")
	public String findTeacherById(HttpServletRequest request,Model model){
		Teacher teacher = (Teacher) request.getSession().getAttribute("teacher");
		Integer id = teacher.getId();
		Teacher teacher2 = this.tImpl.findTeacherById(id);
		model.addAttribute("findTeacher", teacher2);
		return "/teainfo.jsp";
	}
	//修改个人信息
	@RequestMapping("updatetea")
	public Object updatetea(Teacher teacher,HttpServletResponse response) throws IOException{
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		boolean b = this.tImpl.updateTeacher(teacher);
		PrintWriter out = response.getWriter();
		if (b) {
			out.print("<script language='javascript'>alert('修改成功');window.location.href='findteacher'</script>");
		}
		out.print("<script language='javascript'>alert('修改失败');window.location.href='findteacher'</script>");
		return out;
	}
	//修改密码
	@RequestMapping("toupdatepwd")
	public String toupdatepwd(@RequestParam("id") Integer id,Model model) throws IOException{
		model.addAttribute("tid", id);
		return "/teaupdatepwd.jsp";
	}
	@RequestMapping("updatepwd")
	public Object updatepwd(@RequestParam("id") Integer id,HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String oldpwd = request.getParameter("oldpwd");
		String newpwd = request.getParameter("newpwd");
		String confirmpwd = request.getParameter("confirmpwd");
		System.out.println(newpwd+"+"+confirmpwd);
		Teacher teacher = this.tImpl.findTeacherById(id);
		PrintWriter writer = response.getWriter();
		if (oldpwd.equals(teacher.getTpassword())) {
			if (newpwd.equals(confirmpwd)) {
				teacher.setTpassword(newpwd);
				this.tImpl.updateTeacher(teacher);
				writer.print("<script language='javascript'>alert('修改成功');window.location.href='teaindex.jsp'</script>");
			}
			writer.print("<script language='javascript'>alert('两次输入的密码不一致');window.location.href='teaupdatepwd.jsp'</script>");
		}
		writer.print("<script language='javascript'>alert('原密码错误');window.location.href='teaupdatepwd.jsp'</script>");
		return writer;
	}
	//开设课程
	@RequestMapping("addcourse")
	public Object toaddcourse(HttpServletRequest request,Course course,HttpServletResponse response) throws IOException{
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//获取登录教师
		Teacher teacher = (Teacher) request.getSession().getAttribute("teacher");
		PrintWriter writer = response.getWriter();
		if (teacher!=null) {
			course.setTeacher(teacher);
			//判断该课程是否为必修课
			//是必修课则将此专业的学生添加到该课程中
			if(course.getStatus()==0){
				//查询该专业的学生列表
				System.out.println("此课程为必修课");
				List<Student> findStudentBySpecialities = this.tImpl.findStudentBySpecialities(course.getCspecialities());
				for(Student student:findStudentBySpecialities){
					List<Course> courselist = student.getCourse();
					courselist.add(course);
					student.setCourse(courselist);
					this.sImpl.updateStudent(student);
				}
				course.setStudent(findStudentBySpecialities);
			}
			boolean b = this.tImpl.addcourse(course);
			if (b) {
				writer.print("<script language='javascript'>alert('添加成功');window.location.href='addcourse.jsp'</script>");
			}
			writer.print("<script language='javascript'>alert('添加失败');window.location.href='addcourse.jsp'</script>");
		}
		writer.print("<script language='javascript'>alert('请先登录');window.location.href='login.jsp'</script>");
		return writer;
	}
	//查询教师开设的课程（根据id）
	@RequestMapping("toaddgrade")
	public String toaddgrade(HttpServletRequest request,Model model){
		Teacher teacher = (Teacher) request.getSession().getAttribute("teacher");
		Integer id=teacher.getId();
		List<Course> courseByTid = this.tImpl.selectCourseByTid(id);
		model.addAttribute("courseByTid", courseByTid);
		if (request.getParameter("cj")!=null) {
			return "/addgrade.jsp";
		}else {
			return "/stubycoulist.jsp";
		}
		
	}
	//录入成绩（单个）
	@RequestMapping("addgrade")
	public Object addGrade(Grade grade,HttpServletResponse response) throws IOException{
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		//查询是否已经录入（以免重复录入成绩）
		Grade gradeBySnoandCno = this.tImpl.findGradeBySnoandCno(grade.getSno(), grade.getCno());
		if (gradeBySnoandCno==null) {
			Course course = this.tImpl.findCourseByCno(grade.getCno());
			Student student = this.tImpl.findStudentBySno(grade.getSno());
			grade.setCourse(course);
			grade.setStudent(student);
		boolean b = this.tImpl.addGrade(grade);
		if (b) {
			writer.print("<script language='javascript'>alert('录入成功');window.location.href='toaddgrade'</script>");
		}
		}
		writer.print("<script language='javascript'>alert('该学生此课程的成绩已经录入');window.location.href='toaddgrade'</script>");
		return writer;
	}
	//录入成绩（批量）
	@RequestMapping(value="batchaddgrade",method=RequestMethod.POST)
	public Object batchAddGrade(HttpServletResponse response,HttpServletRequest request,@RequestParam("cno") String cno,@RequestParam("file") MultipartFile file) throws IOException{
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		Course course = this.tImpl.findCourseByCno(cno);
		if (!file.isEmpty()) {
			File file2=new File(request.getServletContext().getRealPath("xls"), file.getOriginalFilename());
			file.transferTo(file2);
			FileInputStream f = new FileInputStream(file2);
			Workbook workbook = new XSSFWorkbook(f);
			Sheet sheet=workbook.getSheetAt(0);
			for(Row row:sheet){
				if (row.getRowNum()<1) {
					continue;
				}
				//查询是否已经录入（以免重复录入成绩）
				Grade gradeBySnoandCno = this.tImpl.findGradeBySnoandCno(row.getCell(0).getStringCellValue(), cno);
				if (gradeBySnoandCno==null) {
					Student student = this.tImpl.findStudentBySno(row.getCell(0).getStringCellValue());
					Grade grade=new Grade();
					grade.setSno(row.getCell(0).getStringCellValue());
					grade.setCno(cno);
					grade.setGrade(Double.parseDouble(row.getCell(1).getStringCellValue()));
					grade.setStudent(student);
					grade.setCourse(course);
					this.tImpl.addGrade(grade);
				}else {
					System.out.println("成绩录入重复："+row.getCell(0).getStringCellValue()+"+"+cno);
				}
			}
			f.close();
			writer.print("<script language='javascript'>alert('成绩批量录入成功');window.location.href='toaddgrade'</script>");
		}
		writer.print("<script language='javascript'>alert('该文件夹为空');window.location.href='toaddgrade'</script>");
		return writer;
	}
	//查看选课学生名单
	@RequestMapping("stubycoulist")
	public String stubycoulist(@RequestParam("cno") String cno,Model model){
		Course course = this.tImpl.findCourseByCno(cno);
		List<Student> stubycoulist = course.getStudent();
		model.addAttribute("cname", course.getCname());
		model.addAttribute("courseByTid", this.tImpl.selectCourseByTid(course.getTeacher().getId()));
		model.addAttribute("stubycoulist", stubycoulist);
		return "/stubycoulist.jsp";
	}

}
